<template>
  <div class="favorites-page">
    <div class="favorites-header">
      <h2>我的收藏</h2>
      <!-- 添加搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索收藏的商品"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
        >
          <template #append>
            <el-button :icon="Search">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <div class="favorites-container">
      <el-row :gutter="20">
        <el-col
          :span="6"
          v-for="item in filteredFavorites"
          :key="item.itemId"
        >
          <el-card class="favorite-item" shadow="hover">
            <img :src="item.image" class="item-image" />
            <div class="item-info">
              <h3>{{ item.title }}</h3>
              <p class="price">¥{{ item.price }}</p>
              <div class="item-actions">
                <el-button type="primary" size="small" @click="addToCart(item)">加入购物车</el-button>
                <el-button type="danger" size="small" @click="removeFromFavorites(item.itemId)">
                  取消收藏
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 空状态展示 -->
      <div v-if="filteredFavorites.length === 0" class="empty-state">
        <el-empty :description="emptyText">
          <el-button type="primary" @click="goToHome">去逛逛</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const favoriteItems = ref([])
const searchQuery = ref('')
const products = ref([]) // 确保这里正确声明了 products

// 过滤收藏商品
const filteredFavorites = computed(() => {
  if (!Array.isArray(favoriteItems.value)) return []
  if (!searchQuery.value) {
    return favoriteItems.value.filter(item => item && item.id !== undefined)
  }
  const query = searchQuery.value.toLowerCase()
  return favoriteItems.value.filter(item =>
    item && item.title && item.title.toLowerCase().includes(query)
  )
})

// 空状态文本
const emptyText = computed(() => {
  return searchQuery.value
    ? '没有找到相关商品'
    : '暂无收藏商品'
})

// 处理搜索
const handleSearch = () => {
  // 这里可以添加防抖逻辑如果需要
  console.log('搜索:', searchQuery.value)
}
// 获取收藏数据
const getFavorites = async () => {
  try {
    const userName = 'admin' // 这里假设用户名是固定的 'admin'，根据实际情况调整
    const response = await axios.get(`/logic/favorites/list/${userName}`)
    products.value = response.data.map(item => ({
      userName: userName,
      itemId: item.itemId,
      itemTitle: item.itemTitle,
      price: item.price,
      selected: false,
      favorite: false
    }))
    if (Array.isArray(response.data)) {
      favoriteItems.value = response.data.map(item => ({
        userName: userName,
        itemId: item.itemId,
        itemTitle: item.itemTitle,
        price: item.price,
        selected: false, // 添加默认未选择的状态
        favorite: true// 确保收藏品标记为已收藏
      }))
    } else {
      console.error('获取的收藏数据不是数组:', response.data)
      ElMessage.error('获取收藏数据失败')
      favoriteItems.value = []
    }
  } catch (error) {
    console.error('获取收藏失败:', error)
    ElMessage.error('获取收藏失败')
    favoriteItems.value = []
  }
}

// 添加到购物车
const addToCart = async (item) => {
  try {
    await axios.post('/cart/add', {
      itemId: item.itemId,
      itemTitle: item.title,
      quantity: 1,
      price: item.price,
      status: item.status
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error('添加失败，请稍后重试')
  }
}

// 从收藏夹移除
const removeFromFavorites = async (itemId) => {
  try {
    await axios.post('/logic/favorites/remove', { itemId: itemId })
    favoriteItems.value = favoriteItems.value.filter(item => item.itemId !== itemId)
    ElMessage.success('已取消收藏')
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

onMounted(() => {
  getFavorites()
})
</script>

<style scoped>
.favorites-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.favorites-container {
  min-height: 400px;
}

.favorite-item {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.favorite-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.item-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.item-info {
  padding: 15px;
}

.item-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.item-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.favorites-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}
</style>
